using System.Collections.Generic;
using System.IO;
using System;
using System.ComponentModel.Composition;
using System.Diagnostics;
using System.Text;
using System.Waf.Applications;
using System.Windows.Input;
using TrackMe.Apps.Views;
using TrackMe.Dto;

namespace TrackMe.Apps.VM
{
	[Export]
	[PartCreationPolicy(CreationPolicy.NonShared)]
	public class ReportVM : BasicViewModel<IReportView>
	{
		private readonly IDatabase database;
		public ICommand ExportToExcelCmd { get; private set; }
		public IList<string> PeriodItems { get; private set; }
		public IList<string> KindItems { get; private set; }

		private int selectedPeriodIndex;
		public int SelectedPeriodIndex
		{
			get { return selectedPeriodIndex; }
			set
			{
				if (selectedPeriodIndex != value)
				{
					Load((ReportPeriod) value, (ReportKind) SelectedKindIndex);
					selectedPeriodIndex = value;
				}
			}
		}

		private int selectedKindIndex;
		public int SelectedKindIndex
		{
			get { return selectedKindIndex; }
			set
			{
				if (selectedKindIndex != value)
				{
					Load((ReportPeriod) selectedPeriodIndex, (ReportKind) value);
					selectedKindIndex = value;
				}
			}
		}

		[ImportingConstructor]
		public ReportVM(IReportView view, IDatabase database) : base(view)
		{
			this.database = database;
			ExportToExcelCmd = new DelegateCommand(ExportToExcel);
			PeriodItems = new List<string>();
			KindItems = new List<string>();
			SetupParams();
		}

		private void SetupParams()
		{
			foreach (var name in Enum.GetNames(typeof (ReportPeriod)))
			{
				PeriodItems.Add(MakePhrase(name));
			}
			
			foreach (var name in Enum.GetNames(typeof (ReportKind)))
			{
				KindItems.Add(MakePhrase(name));
			}
		}

		private static string MakePhrase(string s)
		{
			var sb = new StringBuilder();
			foreach (char t in s)
			{
				if (Char.IsUpper(t))
					sb.Append(" ");
				sb.Append(t);
			}
			return sb.ToString();
		}

		private void Load(ReportPeriod period, ReportKind kind)
		{
			ViewCore.Clear();
			Model = database.Report(period, kind);
			int index = 0;
			foreach (var column in Model.Columns)
			{
				ViewCore.AddColumn(string.Format("[{0}]", index++), column);
			}
			foreach (var cell in Model.Cells)
			{
				ViewCore.AddRow(cell);
			}
			RaisePropertyChanged(() => Model);
		}

		public IReport Model { get; private set; }

		public string GetTemporaryFile(string extn)
		{ 
			if (!extn.StartsWith("."))
				extn = "." + extn;
			return Path.GetTempPath() + Guid.NewGuid() + extn;
		}

		private void ExportToExcel()
		{
			string temporaryFile = GetTemporaryFile("xls");
			SaveToExcelFile(temporaryFile);
			Process.Start(temporaryFile);
		}

		public void SaveToExcelFile(string fileName)
		{
			var excelDoc = new StreamWriter(fileName);
			const string startExcelXML = "<xml version>\r\n<Workbook " +
				  "xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\"\r\n" +
				  " xmlns:o=\"urn:schemas-microsoft-com:office:office\"\r\n " +
				  "xmlns:x=\"urn:schemas-    microsoft-com:office:" +
				  "excel\"\r\n xmlns:ss=\"urn:schemas-microsoft-com:" +
				  "office:spreadsheet\">\r\n <Styles>\r\n " +
				  "<Style ss:ID=\"Default\" ss:Name=\"Normal\">\r\n " +
				  "<Alignment ss:Vertical=\"Bottom\"/>\r\n <Borders/>" +
				  "\r\n <Font/>\r\n <Interior/>\r\n <NumberFormat/>" +
				  "\r\n <Protection/>\r\n </Style>\r\n " +
				  "<Style ss:ID=\"BoldColumn\">\r\n <Font " +
				  "x:Family=\"Swiss\" ss:Bold=\"1\"/>\r\n </Style>\r\n " +
				  "<Style     ss:ID=\"StringLiteral\">\r\n <NumberFormat" +
				  " ss:Format=\"@\"/>\r\n </Style>\r\n <Style " +
				  "ss:ID=\"Decimal\">\r\n <NumberFormat " +
				  "ss:Format=\"0.0000\"/>\r\n </Style>\r\n " +
				  "<Style ss:ID=\"Integer\">\r\n <NumberFormat " +
				  "ss:Format=\"0\"/>\r\n </Style>\r\n <Style " +
				  "ss:ID=\"DateLiteral\">\r\n <NumberFormat " +
				  "ss:Format=\"mm/dd/yyyy;@\"/>\r\n </Style>\r\n " +
				  "</Styles>\r\n ";
			const string endExcelXML = "</Workbook>";

			int rowCount = 0;
			int sheetCount = 1;
			/*
		   <xml version>
		   <Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
		   xmlns:o="urn:schemas-microsoft-com:office:office"
		   xmlns:x="urn:schemas-microsoft-com:office:excel"
		   xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet">
		   <Styles>
		   <Style ss:ID="Default" ss:Name="Normal">
			 <Alignment ss:Vertical="Bottom"/>
			 <Borders/>
			 <Font/>
			 <Interior/>
			 <NumberFormat/>
			 <Protection/>
		   </Style>
		   <Style ss:ID="BoldColumn">
			 <Font x:Family="Swiss" ss:Bold="1"/>
		   </Style>
		   <Style ss:ID="StringLiteral">
			 <NumberFormat ss:Format="@"/>
		   </Style>
		   <Style ss:ID="Decimal">
			 <NumberFormat ss:Format="0.0000"/>
		   </Style>
		   <Style ss:ID="Integer">
			 <NumberFormat ss:Format="0"/>
		   </Style>
		   <Style ss:ID="DateLiteral">
			 <NumberFormat ss:Format="mm/dd/yyyy;@"/>
		   </Style>
		   </Styles>
		   <Worksheet ss:Name="Sheet1">
		   </Worksheet>
		   </Workbook>
		   */
			excelDoc.Write(startExcelXML);
			excelDoc.Write("<Worksheet ss:Name=\"Sheet" + sheetCount + "\">");
			excelDoc.Write("<Table>");
			excelDoc.Write("<Row>");
			foreach (string t in Model.Columns)
			{
				excelDoc.Write("<Cell ss:StyleID=\"BoldColumn\"><Data ss:Type=\"String\">");
				excelDoc.Write(t);
				excelDoc.Write("</Data></Cell>");
			}
			excelDoc.Write("</Row>");
			foreach (var x in Model.Cells)
			{
				rowCount++;
				//if the number of rows is > 64000 create a new page to continue output

				if (rowCount == 64000)
				{
					rowCount = 0;
					sheetCount++;
					excelDoc.Write("</Table>");
					excelDoc.Write(" </Worksheet>");
					excelDoc.Write("<Worksheet ss:Name=\"Sheet" + sheetCount + "\">");
					excelDoc.Write("<Table>");
				}
				excelDoc.Write("<Row>"); //ID=" + rowCount + "

				for (int y = 0; y < Model.Columns.Length; y++)
				{
					Type rowType = x[y].GetType();
					switch (rowType.ToString())
					{
						case "System.String":
							string XMLstring = x[y].ToString();
							XMLstring = XMLstring.Trim();
							XMLstring = XMLstring.Replace("&", "&");
							XMLstring = XMLstring.Replace(">", ">");
							XMLstring = XMLstring.Replace("<", "<");
							excelDoc.Write("<Cell ss:StyleID=\"StringLiteral\">" +
										   "<Data ss:Type=\"String\">");
							excelDoc.Write(XMLstring);
							excelDoc.Write("</Data></Cell>");
							break;
						case "System.DateTime":
							//Excel has a specific Date Format of YYYY-MM-DD followed by  

							//the letter 'T' then hh:mm:sss.lll Example 2005-01-31T24:01:21.000

							//The Following Code puts the date stored in XMLDate 

							//to the format above

							var XMLDate = (DateTime)x[y];

							string XMLDatetoString = XMLDate.Year +
								"-" +
									(XMLDate.Month < 10 ? "0" +
										XMLDate.Month : XMLDate.Month.ToString()) +
											"-" +
												(XMLDate.Day < 10 ? "0" +
													XMLDate.Day : XMLDate.Day.ToString()) +
														"T" +
															(XMLDate.Hour < 10 ? "0" +
																XMLDate.Hour : XMLDate.Hour.ToString()) +
																	":" +
																		(XMLDate.Minute < 10 ? "0" +
																			XMLDate.Minute : XMLDate.Minute.ToString()) +
																				":" +
																					(XMLDate.Second < 10 ? "0" +
																						XMLDate.Second : XMLDate.Second.ToString()) +
																							".000";
							excelDoc.Write("<Cell ss:StyleID=\"DateLiteral\">" +
										 "<Data ss:Type=\"DateTime\">");
							excelDoc.Write(XMLDatetoString);
							excelDoc.Write("</Data></Cell>");
							break;
						case "System.Boolean":
							excelDoc.Write("<Cell ss:StyleID=\"StringLiteral\">" +
										"<Data ss:Type=\"String\">");
							excelDoc.Write(x[y].ToString());
							excelDoc.Write("</Data></Cell>");
							break;
						case "System.Int16":
						case "System.Int32":
						case "System.Int64":
						case "System.Byte":
							excelDoc.Write("<Cell ss:StyleID=\"Integer\">" +
									"<Data ss:Type=\"Number\">");
							excelDoc.Write(x[y].ToString());
							excelDoc.Write("</Data></Cell>");
							break;
						case "System.Decimal":
						case "System.Double":
							excelDoc.Write("<Cell ss:StyleID=\"Decimal\">" +
								  "<Data ss:Type=\"Number\">");
							excelDoc.Write(x[y].ToString());
							excelDoc.Write("</Data></Cell>");
							break;
						case "System.DBNull":
							excelDoc.Write("<Cell ss:StyleID=\"StringLiteral\">" +
								  "<Data ss:Type=\"String\">");
							excelDoc.Write("");
							excelDoc.Write("</Data></Cell>");
							break;
						default:
							throw (new Exception(rowType + " not handled."));
					}
				}
				excelDoc.Write("</Row>");
			}
			excelDoc.Write("</Table>");
			excelDoc.Write(" </Worksheet>");
			excelDoc.Write(endExcelXML);
			excelDoc.Close();
		}

	}

}